package security

import (
	"cps-user/model/global"
	"github.com/gin-gonic/gin"
	"gopkg.in/boj/redistore.v1"
	"log"
	"net/http"
)

var SessionManager *redistore.RediStore

var whiteList = map[string]bool{"/login": true}

func LoginIntercept() gin.HandlerFunc {
	return func(c *gin.Context) {
		url := c.Request.URL.String()
		if whiteList[url] {
			c.Next()
			return
		}
		auth(c)
	}
}

func auth(c *gin.Context) {
	session, err := SessionManager.Get(c.Request, global.GlobalConfig.SessionKey)
	if err != nil {
		log.Fatal(err)
	}
	if session.IsNew {
		c.JSON(http.StatusBadRequest, "未登录")
	}
	if err := session.Save(c.Request, c.Writer); err != nil {
		log.Fatal(err)
	}
	c.Next()

}

func Load() gin.HandlerFunc {
	return func(c *gin.Context) {

		SessionManager = newSessionManager()
	}
}

func newSessionManager() *redistore.RediStore {
	//redistore, err := redistore.NewRediStore(10, "tcp", ":6379", "", []byte(global.GlobalConfig.SessionKey))
	store, err := redistore.NewRediStore(10, "tcp", ":6379", "", []byte(global.GlobalConfig.SessionKey))
	if err != nil {
		panic(err)
	}
	return store
}
